package com.element.feign.config;

import com.common.core.constant.SecurityHeader;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @auther zhangwj
 * @date 2021/5/13 下午6:17
 */
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                String token = request.getHeader(SecurityHeader.AUTH_SECURITY_HEADERS);
                if (StringUtils.hasText(token)) {
                    requestTemplate.header(SecurityHeader.AUTH_SECURITY_HEADERS, token);
                } else {
                    token = request.getParameter(SecurityHeader.AUTH_SECURITY_HEADERS);
                    if (StringUtils.hasText(token)) {
                        requestTemplate.header(SecurityHeader.AUTH_SECURITY_HEADERS, (SecurityHeader.AUTH_SECURITY_VALUE + " " + token));
                    }
                }
            }
        };
    }
}
